package com.woniu.sharepark.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName: UploadImageUtil
 * @Description: 此类为图片上传配置类，可以执行所有图片上传的操作
 * @Author: Zongjie.Li
 * @Date: 2019/6/5
 * @Version: 1.0
 **/
@Component
public class UploadImageUtil {

    private static String systemPath;

    public static void setSystemPath(String path){
        systemPath = path;
    }

    public static String getSystemPath() {
        return systemPath;
    }

    /**
    * 将图片上传至指定文件夹下，返回新的文件名
    *
    * @param multipartFile 此参数为前端传进来的文件
    * @return java.lang.String
    * @Author Zongjie.Li
    * @Date 2019/6/5
    */
    public static String uploadImage(MultipartFile multipartFile) throws IOException {
        File fileDirectory = new File(systemPath);
        if (!fileDirectory.exists()) {
            fileDirectory.mkdirs();
        }
        String[] name = multipartFile.getOriginalFilename().split("\\.");
        String fileName = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + new Random().nextInt(9999) + "." + name[name.length - 1];
        File fileImage = new File(systemPath + fileName);
        multipartFile.transferTo(fileImage);
        return fileName;
    }
}
